<!--
 * @Descripttion: 
 * @version: 
 * @Author: zhangzhanhua
 * @Date: 2021-01-08 19:56:21
 * @LastEditors: zhangzhanhua
 * @LastEditTime: 2021-01-21 19:24:32
-->
<script>
import { actions } from "../../../store/index";
import EmojiInputMethod from "./ImojiIndex";
export default {
  vuex: {
    actions: actions,
  },
  components: {
    EmojiInputMethod,
  },
  data() {
    return {
      content: "",
      path: "ws://192.168.75.133:9898/ws",
      ws: this.$store.state.wsobj,
      showFacePanel: false,
      drawer: false,
      historyDataMessage: [],
    };
  },
  props: {
    sendhandler: {
      type: Function,
    },
  },
  created() { },
  mounted() {
    this.init();
  },
  methods: {
    handleFaceChoose(face) {
      const value = this.content;
      const el = this.$refs.shareTextArea;
      const startPos = el.selectionStart;
      const endPos = el.selectionEnd;
      const newValue =
        value.substring(0, startPos) +
        face +
        value.substring(endPos, value.length);
      this.content = newValue;
      if (el.setSelectionRange) {
        setTimeout(() => {
          const index = startPos + face.length;
          el.setSelectionRange(index, index);
        }, 0);
      }
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => { });
    },
    sendMessageClick() {
      if (this.content.trim().length != 0) {
        this.$store.commit("SEND_MESSAGE", this.content);
        var params = {
          id: "2",
          to: this.$store.state.currentSessionId,
          action: "push",
          content: this.content,
        };
        this.ws.send(JSON.stringify(params));
        this.sendhandler(this.content);
        this.$store.commit("sendContentNew", this.content);
        this.content = "";
      }
    },
    onKeyup(e) {
      if (e.keyCode === 13 && this.content.trim().length) {
        // if (this.content.trim().length == 0) {return}
        console.log(this.$store.state.sessions[0].accNo, "000000");
        // alert(state.currentSessionId)
        // actions.sendMessage(this.content);
        // this.ws.send('测试消息');
        // this.init(this.content)
        console.log(this.content, "this.content");
        this.$store.commit("SEND_MESSAGE", this.content);
        var params = {
          id: "2",
          to: this.$store.state.currentSessionId,
          action: "push",
          content: this.content,
        };
        this.ws.send(JSON.stringify(params));
        this.sendhandler(this.content);
        this.$store.commit("sendContentNew", this.content);
        this.content = "";
      }
    },
    //init函数可在页面加载的时候就进行初始化或者根据自己的业务需求在需要打开通讯的时候在进行初始化
    init() {
      // 实例化socket，这里的实例化直接赋值给this.ws是为了后面可以在其它的函数中也能调用websocket方法，例如：this.ws.close(); 完成通信后关闭WebSocket连接
      // this.ws = new WebSocket(this.path)
      //  console.log(this.ws,'this.ws')
      //监听是否连接成功
      // this.ws.onopen = ()=> {
      //      console.log('ws连接状态：' +this.ws.readyState);
      //      var data = {
      //          token:window.sessionStorage.getItem('token'),
      //          action:"login"
      //      }
      //      this.ws.send(JSON.stringify(data));
      //   }

      //接听服务器发回的信息并处理展示
      this.ws.onmessage = (data) => {
        console.log(data, "服务器返回的消息～");
        var messageNew = JSON.parse(data.data);
        var getmessages = localStorage.getItem("messages");
        getmessages = getmessages ? JSON.parse(getmessages) : [];
        console.log(messageNew.success, "messageNew.success");
        if (messageNew.msg == '读取成功~') {
          this.historyDataMessage = messageNew.data.pages
          this.personSession = messageNew
        }
        this.$store.commit("successStatus", messageNew.success);
         messageNew.success?'':this.$message.error(messageNew.msg)
        if (messageNew.fileId == undefined) {
          return;
        } else {
          if (
            messageNew.accForm == undefined &&
            messageNew.accForm == "" &&
            messageNew.accForm == null
          ) {
            getmessages.push({
              content: messageNew.content,
              date: new Date(),
              self: true,
              success:messageNew.success
            });
            this.$store.commit("insertMessage", getmessages);
            localStorage.setItem("messages", JSON.stringify(getmessages));
            this.sendhandler(messageNew.content);
          } else {
            getmessages.push({
              content: messageNew.content,
              date: new Date(),
              self: false,
              success:messageNew.success
            });
            this.$store.commit("insertMessage", getmessages);
            localStorage.setItem("messages", JSON.stringify(getmessages));
            this.sendhandler(messageNew.content);
          }
        }

        //  if(data.data.accFrom == 'zhangzh') {

        //  }
        //  this.$store.state.sessions[0].messages = data.data
      };

      //  //监听连接关闭事件
      //  this.ws.onclose = ()=>{
      //     //监听整个过程中websocket的状态
      //     console.log('ws连接状态：' + this.ws.readyState);
      //  }

      //  //监听并处理error事件
      //  this.ws.onerror = function(error) {
      //     console.log(error);
      //  }
    },
    historyData() {
      this.drawer = true;
      var listData = {
        startpage: "",
        pagesize: "",
        action: "pull",
        from: this.$store.state.currentSessionId
      };
      this.ws.send(JSON.stringify(listData));
    },
    maskClick() {
      this.drawer = false
    }
  },
};
</script>

<template>
  <div class="text">
    <emoji-input-method @onFaceChoose="handleFaceChoose" v-if="showFacePanel"></emoji-input-method>
    <div style="background-color: white; padding: 10px 0 0 5px">
      <img @click="showFacePanel = true" style="
          width: 16px;
          border-radius: 50px;
          margin-right: 15px;
          margin-left: 8px;
        " src="@/assets/svg/smileIcon.svg" />
      <img @click="historyData" style="width: 16px; border-radius: 50px" src="@/assets/svg/histroyList.svg" />
    </div>
    <textarea @focus="showFacePanel = false" placeholder="按 Enter 发送" v-model="content" @keyup="onKeyup" ref="shareTextArea"></textarea>
    <el-button style="position: relative; top: -100px; float: right; margin-right: 20px" @click="sendMessageClick">发送</el-button>
    <!-- <el-dialog width="65%" center title="历史消息" :visible.sync="drawer" :before-close="handleClose"> -->
    <div class="historyM" v-if="drawer">
      <div class="mask" @click="maskClick()"></div>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>历史消息</span>
          <i class="el-icon-close" style="float: right; padding: 3px 0" type="text" @click="()=>{this.drawer = false}"></i>
        </div>
        <div class="HMessage">
          <ul style="padding:0px 10px">
            <li class="historyStyle" v-for="(item,index) in historyDataMessage" :key="index">
              <div style="display:flex">
                <div class="floatL" style="padding:0px 15px">
                  <img :src="personSession.avatar" width="32px" height="32px" />
                </div>
                <div class="floatL" style="width:100%">
                  <div style="color:#909399">
                    <span>{{personSession.accName}}</span>
                    <span style="float:right;min-width:140px;">{{item.createTime}}</span>
                  </div>
                  <div style="padding:10px 40px 0px 0px;line-height:1.5">
                    <span>{{item.content}}</span>
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </el-card>

    </div>

    <!-- </el-dialog> -->
  </div>
</template>
<style>
/* .v-modal{
    z-index:9!important;   
}
.el-drawer{
    height: 73%!important;
    width: 35%!important;
    margin: 0 auto;
    margin-top: 7%;
}
.el-drawer__body{
    background-color: rgb(243, 243, 249);
    overflow: scroll;
}
.el-drawer__header{
    padding:10px 20px!important;
    margin-bottom: 0!important;
    font-size: 14px;
    color: #333!important;

} */
</style>
<style lang="less" scoped>
.box-card{
  width: 65%;
  height: 75%;
  z-index: 9999;

  /deep/ .el-card__body{
    height: 100%;
    // overflow-y: scroll;
  }
}
.historyM {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
  .mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}
.HMessage {
  width: 100%;
  height: 100%;
  background-color: #fff;
  z-index: 1551;
  overflow-y: scroll;
}
.historyStyle {
  display: inline-block;
  width: 100%;
  padding: 15px 0px;
  border-top: 1px solid #d8d8d8;
}
.floatL {
  float: left;
}
.text {
  height: 160px;
  border-top: solid 1px #ddd;

  textarea {
    padding: 10px;
    height: 100%;
    width: 100%;
    border: none;
    outline: none;
    font-family: "Micrsofot Yahei";
    resize: none;
    background-color: white;
  }
}
</style>